<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" >
				<el-form-item>
					<el-input v-model="keyword" placeholder="姓名"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="keywordQuery">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="departments" highlight-current-row v-loading="listLoading"
      :row-key="getRowKeys"   ref="DepartmentTable"    @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55" reserve-selection="true" >
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="sn" label="部门编号" width="120" sortable>
			</el-table-column>
			<el-table-column prop="name" label="部门名称" width="100" sortable>
			</el-table-column>
			<el-table-column prop="dirPath" label="部门层级" width="100" sortable>
			</el-table-column>
      <el-table-column prop="state" label="状态" width="100" sortable>
        <template scope="scope">
          <span v-if="scope.row.state==1" style="color: #13ce66">启用</span>
          <span v-else-if="scope.row.state==0" style="color: #8c939d">禁用</span>
        </template>
      </el-table-column>
			<el-table-column prop="employee.username" label="管理员" width="120" sortable>
			</el-table-column>
			<el-table-column prop="department.name" label="上级部门" min-width="180" sortable>
			</el-table-column>
			<el-table-column label="操作">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totals" style="float:right">
      </el-pagination>
<!--      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
         :current-page="currentPage" :page-size="pageSize" :total="totals" style="float:right;">
			</el-pagination>-->
		</el-col>
		<!--新增/修改界面-->
		<el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm"
      :before-close="saveFormClose" >
				<el-form-item label="部门编号" prop="sn">
					<el-input v-model="saveForm.sn" auto-complete="off" @focus="nextTick('sn')"></el-input>
				</el-form-item>
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off" @focus="nextTick('name')"></el-input>
        </el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="saveForm.state">
						<el-radio class="radio" :label="1">启用</el-radio>
						<el-radio class="radio" :label="0">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="管理员">
          <!--el-select下拉框
            v-model="saveForm,manager._id"回显提交的内容的key
            placeholder="请选择"提示语
            el-option选项
            V-for="manager in managers"遍历
            :label="manager.label"回显内容
            :valve=:"manager,valve"提交的内容-->
          <el-select v-model="saveForm.manager_id" placeholder="请选择">
            <el-option
                v-for="item in managers"
                :label="item.username"
                :value="item.id">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
				</el-form-item>

          <!--
             :options="options" - 数据 - 无限极树- 集合
                     label:'name' - 回显哪一个属性值
                     value:'id' - 传值，将id传递给v-model="saveForm.parent_id"
             回显机制：
             1. 先根据【v-model="saveForm.parent_id"】parent_id与deptTree中的每一个对象进行比对
             2. 比对到之后回显对象的哪一个属性【label: 'name'】对象的name属性值
             传值机制：
             1. 当选择一个上级部门之后将部门的id【value: 'id'】
             2. 传值给【v-model="saveForm.parent_id"】parent_id，最后更新到数据库
           -->
        <el-form-item label="上级部门">
          <el-cascader v-model="saveForm.parent_id"
                       :options="deptTree"
                       :props="{
            	checkStrictly: true,
                label: 'name', // 级联框显示那个属性的值
                value: 'id'    // 回显时需要,回传值的时候也需要
            }" clearable>
          </el-cascader>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getDepartmentListPage, removeDepartment, batchRemoveDepartment, editDepartment, addDepartment } from '../../api/api';

	export default {
		data() {
			return {

        keyword: '',
        departments: [],
        totals: 0,
        currentPage: 1,
        pageSize:5,
        listLoading: false,
        sels: [],//列表选中列
        title:'',
        saveFormVisible: false,//新增界面是否显示
        saveLoading: false,
        saveFormRules: {
          name: [
            {required: true, message: '请输入部门名称', trigger: 'blur'},

          ],
          sn: [
            {required: true, message: '请输入部门编号', trigger: 'blur'}
          ],

        },
        //新增界面数据
        saveForm: {
          sn:'',
          name:'',
          state:null,
          manager_id:null,
          parent_id:null,
        },
        //所有管理员
        managers:[],
        //模型数据data：
        //部门树
        deptTree: [],
      }
    },
		methods: {
			// //性别显示转换
			// formatSex: function (row, column) {
			// 	return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
			// },
      nextTick(prop){
        this.$refs.saveForm.clearValidate(prop);
      },
      getRowKeys(row){
        return row.id;
      },
      //获取部门树 - 无线级联
      getDeptTree(id){
        this.$http.get("/department/deptTree/"+id).then(res=> {
          this.deptTree = res.data;
        }).catch(res=>{
          this.$message.error("网络繁忙，请稍后重试")
        })
      },
      keywordQuery(){
        this.currentPage=1;
        this.getDepartments();
      },
			handleCurrentChange(currentPage) {
				this.currentPage = currentPage;
				this.getDepartments();
			},
      handleSizeChange(pageSize){
        this.pageSize=pageSize;
        this.getDepartments();
      },
			//获取用户列表
			getDepartments() {
				let temp = {
          currentPage: this.currentPage,
          pageSize:this.pageSize,
          keyword: this.keyword
				};
				this.listLoading = true;
				//NProgress.start();
				this.$http.post("/department",temp).then((res) => {
					this.totals = res.data.totals;
					this.departments = res.data.data;
					this.listLoading = false;
					//NProgress.done();
				}).catch(res=>{
          this.$message.error("网络繁忙，请稍后重试")
        });
			},
      //获取所有管理员
      getManagers(){
        this.$http.get("/employee").then(res=>{
          this.managers=res.data;
        }).catch(res=>{
          this.$message.error("网络繁忙，请稍后重试【404】")
        })
      },
			//删除
      handleDel: function (index, row) {
        this.$confirm('确认删除该记录吗?', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          //NProgress.start();
          // let temp = { id: row.id };
          this.$http.delete("/department/" + row.id).then(res => {
            this.listLoading = false;
            if (res.data.success) {
              this.$message.success(res.data.message);
              if (this.currentPage != 1 && this.totals % this.pageSize == 1
                  && this.currentPage == Math.ceil(this.totals / this.pageSize)) {
                this.currentPage = this.currentPage - 1;
              }
              this.getDepartments();
            } else {
              this.$message.error(res.data.message);
            }
          }).catch(res => {
            this.$message.error("网络繁忙，请稍后重试【404】")
          })
        }).catch(() => {
          this.$message.info("操作取消")
        });
      },
      //显示编辑界面
      handleEdit: function (index, row) {
        this.title='编辑';
        //复制数据
        this.saveForm = Object.assign({}, row);
        //获取所有员工信息
        this.getManagers();
        //获取部门树
        this.getDeptTree(row.id);
        //打开对话框
        this.saveFormVisible = true;
      },
      //显示新增界面
      handleAdd: function () {
        this.title='新增';
        this.getManagers();
        //获取部门树
        this.getDeptTree(-1);
        this.saveForm = {
          sn:'',
          name:'',
          state:0,
          manager_id: null,
          parent_id:null,
        };
        //打开对话框
        this.saveFormVisible = true;
      },
      //新增/编辑
      saveSubmit: function () {
        this.$refs.saveForm.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.saveLoading = true;
              //NProgress.start();
              let temps = Object.assign({}, this.saveForm);
              let temp = temps.parent_id;
              if (temp && temp.length==0 ){
                temps.parent_id=null;
              }else if (temp && temp.length>0) {
                temps.parent_id=temp[temp.length-1];
              }
              this.$http.put("/department",temps).then(res=>{
                this.saveLoading=false;
                if (res.data.success){
                  this.saveFormVisible = false;
                  this.$message.success(res.data.message);
                  if (this.title=='新增' && this.totals%this.pageSize==0){
                    this.totals+=1;
                  }
                  if (this.title=='新增'){
                    this.currentPage=Math.ceil(this.totals/this.pageSize);
                  }
                    this.getDepartments();
                }else {
                  this.$message.error(res.data.message);
                }
              }).catch(res=>{{
                this.$message.error("网络繁忙，请稍后重试【404】")
              }})
            }).catch(()=>{
              this.$message.info("操作取消");
            });
          }
        });
      },
      selsChange: function (rows) {
        //map相当于循环变量，遍历后我取出id,就变成id的数组
        this.sels = rows.map(dept => dept.id);
      },
      //批量删除
      batchRemove: function () {
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          // NProgress.start();
          // let temp = { ids: ids };
          this.$http.patch("/department", this.sels).then(res => {
            this.listLoading = false;
            if (res.data.success) {
              this.$message.success(res.data.message);
              this.sels=[],
              //清空多选框
              this.$refs.DepartmentTable.clearSelection();
              this.currentPage=1;
              this.getDepartments();
            } else {
              this.$message.error(res.data.message);
            }
          }).catch(res => {
            this.$message.error("网络繁忙，请稍后重试【404】")
          })
        }).catch(() => {
          this.$message.info("操作取消")
        });
      },
      //编辑
      editSubmit: function () {
        this.$refs.editForm.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.editLoading = true;
              //NProgress.start();
              let temp = Object.assign({}, this.editForm);
              temp.birth = (!temp.birth || temp.birth == '') ? '' : util.formatDate.format(new Date(temp.birth), 'yyyy-MM-dd');
              editDepartment(temp).then((res) => {
                this.editLoading = false;
                //NProgress.done();
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
                this.$refs['editForm'].resetFields();
                this.editFormVisible = false;
                this.getDepartments();
              });
            });
          }
        });
      },
    },
    mounted() {
      this.getDepartments();
		}
	}

</script>

<style scoped>

</style>